<template>
  <div class="home">

    <div class="home-container">
      <div class="home-menu"><!-- 这里表示侧边栏的菜单 -->

        <div class="menu-header">
          <img class="user-avatar" :src="currentUser.headImage"/>
          <div class="user-profile">
            <div class="user-profile-main">
              <div class="user-profile-header">
                <img :src="currentUser.headImage"/>
                <div>{{ currentUser.nickName }}</div>
              </div>
              <div class="user-profile-info">
                <div class="user-profile-info-title">邮箱</div>
                <div>{{ currentUser.email }}</div>
              </div>
              <div class="user-profile-info">
                <div class="user-profile-info-title">手机</div>
                <div>{{ currentUser.phone }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="menu-box">
          <div class="menu-list">
            <div class="menu-item" :class="{'router-link-active':componentName==='ConversationsPrivate'}"
                 @click="componentName='ConversationsPrivate'">
              <i class="iconfont icon-xiaoxi-xiaoxi"></i>
              <span v-if="unreadAmountPrivate" class="menu-unread" style="box-shadow: #f7f7f7 0 0 0 2px;">{{ unreadAmountPrivate }}</span>
            </div>
            <div class="menu-item" :class="{'router-link-active':componentName==='ConversationsGroup'}"
                 @click="componentName='ConversationsGroup'">
              <i class="iconfont icon-zaixiankefu"></i>
              <span v-if="unreadAmountGroup" class="menu-unread" style="box-shadow: #f7f7f7 0 0 0 2px;">{{ unreadAmountGroup }}</span>
            </div>
            <hr style="width: 70%">
            <div class="menu-item" :class="{'router-link-active':componentName==='contacts'}"
                 @click="componentName='contacts'">
              <i class="iconfont icon-haoyou"></i>
            </div>
            <div class="menu-item" :class="{'router-link-active':componentName==='addFriendOrGroup'}"
                 @click="componentName='addFriendOrGroup'">
              <i class="iconfont icon-zengjia"></i>
            </div>

            <!--            <router-link tag="div" class="menu-item" to="/conversations" replace>-->
            <!--              <i class="iconfont icon-zaixiankefu"></i>-->
            <!--              <span v-if="unreadAmount" class="menu-unread">{{ unreadAmount}}</span>-->
            <!--            </router-link>-->
            <!--            <router-link tag="div" class="menu-item" to="/contacts" replace>-->
            <!--              <i class="iconfont icon-haoyou"></i>-->
            <!--            </router-link>-->
          </div>
          <div class="exit">
            <i class="iconfont icon-h" @click="logout"></i>
          </div>
        </div>
      </div>

      <div class="home-main">
        <div v-if="">

        </div>
        <Component :is="componentName"
                   :currentUser="currentUser"
                   :chatFriend="chatFriend"
                   :stompClient="stompClient"
                   :messagePrivateCheck="messagePrivate"
                   :messageGroup="messageGroup"
                   :systemUser="systemUser"
                   v-on:chatFriend="chooseChatFriend"
                   v-on:chatGroup="chooseChatGroup"
        ></Component>
      </div>

    </div>

    <!-- 添加或修改聊天用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="是否商家" prop="business">
          <el-radio v-model="form.business" label="0">否</el-radio>
          <el-radio v-model="form.business" label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <image-upload v-model="form.headImage"/>
        </el-form-item>
<!--        <el-form-item label="系统登录id" prop="systemId">-->
<!--          <el-input v-model="form.systemId" placeholder="请输入系统登录id" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
<!--        <el-button @click="cancel">取 消</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ConversationsPrivate from "@/views/chat/session/ConversationsPrivate";//单聊聊天目录展示
import ConversationsGroup from "@/views/chat/session/ConversationsGroup";//群聊聊天目录
import contacts from "@/views/chat/session/Contacts";
import addFriendOrGroup from "@/views/chat/session/AddFriendOrGroup";
import {addUser,  getUserBySystemId,  updateUser} from "@/api/chat/user";
import {getUserInfo} from "@/api/system/user";
import Stomp from "stompjs";

export default {
  components: {
    ConversationsPrivate,ConversationsGroup, contacts,addFriendOrGroup
  },
  data() {
    return {
      componentName: "",
      currentUser: {},//当前用户数据
      systemUser:{},//用来存和当前用户对应的系统用户数据
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 添加用户时表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
      },
      unreadAmountPrivate: 0,//该变量用于私聊未读消息数量
      unreadAmountGroup: 0,//该变量用于私聊未读消息数量

      chatFriend:0,//临时存一下要聊的好友，用于组件间传值给私聊模块
      chatGroup:null,
      stompClient:null,
      messagePrivate: {},//收取到的私聊即时通讯
      messageGroup: {}//收到的群消息
    };
  },
  created() {

    this.getCurrentUser()
  },
  methods: {
    getCurrentUser(){
      //获取当前登录用户的数据
      // console.info(this.$store.getters.name)
      getUserInfo().then(response => {
        this.systemUser = response.user
        getUserBySystemId(this.systemUser.userId).then(response => {
          //根据系统用户id查询到当前登录的聊天用户信息
          if (response.data){
            this.currentUser = response.data;

            this.initWebsocket();//链接通讯
            this.componentName='ConversationsPrivate'
          }else {
            this.handleAdd()//如果没有该聊天用户，创建一个
          }
        });
      });
    },
    initWebsocket() {
      let ws = new WebSocket('ws://localhost:8080/chat/ws');
      //1.链接用Stomp包裹一下WebSocket
      this.stompClient = Stomp.over(ws);
      //2.初始化链接操作：发送的消息头信息,链接成功时的回调函数 onConnected,链接失败时的回调函数 onError
      this.stompClient.connect({login:this.currentUser.nickName,passcode:123456}, this.onConnected, this.onError);//连接
    },
    onConnected(){
      //
      //订阅/topic/public 订阅公开消息
      this.stompClient.subscribe('/topic/public', (m) => {
        let message = JSON.parse(m.body);
      });

      //给后台发送消息，当前这个会话用户名
      // this.stompClient.send("/chat/addUser", {}, JSON.stringify({sender: Math.random(), type: 'JOIN'}))
      //订阅单发
      this.stompClient.subscribe(`/user/${this.currentUser.nickName}/private`, (m) => {
        let message = JSON.parse(m.body);//json
        this.messagePrivate = {
          id:message.id,
          userIdPash:message.sendUserId,
          pashName:message.sendName,
          pashHeader:message.sendHeader,
          userIdPull:message.userIdPull,
          pullName:message.pullName,
          pullHeader:message.pullHeader,
          messgeText:message.messageText,
          messgeLink:message.messageLink,
          messgeImage:message.messageImage,
          readStatus:0,
          createTime:message.createTime,
          updateTime:null,
          recalled:message.recalled
        }
        console.info("结果")
        console.info(this.messagePrivate)
      })

      //订阅群信息（现在的问题是，如何订阅不同的群）
      this.stompClient.subscribe(`/group/${this.currentUser.id}`, (m) => {
        let message = JSON.parse(m.body);
        this.messageGroup = message
      })
      // this.group.forEach(o=>{
      //   if (o.userId.includes(this.currentUser.id)) {
      //     this.stompClient.subscribe(`/group/${o.name}`, (m) => {
      //       let message = JSON.parse(m.body);
      //       this.messages.push(message);
      //     })
      //   }
      // })
    },
    setUnreadNumber(content) {//该变量用于私聊未读消息数量
      this.unreadAmount = content.unreadTotal;
    },
    chooseChatFriend(chatFriend){//打开私聊页面
      this.chatFriend = chatFriend;
      this.componentName = "ConversationsPrivate";
    },

    chooseChatGroup(chatGroup){//打开私聊页面
      this.chatGroup = chatGroup;
      this.componentName = "ConversationsGroup";
    },
    logout() {
      if (confirm('确认要退出登录吗？')) {
        // this.goEasy.disconnect({
        //   onSuccess: () => {
        //     this.globalData.currentUser = null;
        //     this.$router.replace({path: './login'});
        //   },
        //   onFailed: (error) => {
        //     console.log("Failed to disconnect GoEasy, code:" + error.code + ",error:" + error.content);
        //   }
        // });
      }
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "您还没有聊天用户，请注册一个聊天用户";
      this.form.systemId = this.systemUser.userId
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickName: null,
        business: '0',
        headImage: null,
        systemId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;

            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getCurrentUser()
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped>
@media screen and (max-width: 1000px) {
  .home-container {
    width: 850px;
    height: 430px;
  }
}

@media screen and (min-width: 1000px) {
  .home-container {
    width: 850px;
    height: 650px;
  }
}

.home {
  margin-top: 20px;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-container {
  background: #FFFFFF;
  display: flex;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.75);
  border-radius: 15px;
  overflow: hidden;
}

.home-menu {
  width: 60px;
  background-color: #F7F7F7;
  border-right: 1px solid #eeeeee;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 15px;
}

.menu-header {
  margin: 20px auto;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  cursor: pointer;
}

.user-avatar:hover + .user-profile {
  display: block;
}

.user-profile {
  display: none;
  color: #FFFFFF;
  position: absolute;
  top: 0;
  left: 70px;
  width: 250px;
  height: 200px;
  background: #FFFFFF;
  z-index: 999;
}

.user-profile-main {
  border: 1px solid #EBEEF5;
  background-color: #FFF;
  color: #303133;
  border-radius: 4px;
}

.user-profile-header {
  padding: 18px 20px;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 15px;
  font-weight: bold;
}

.user-profile-header img {
  width: 45px;
  height: 45px;
}

.user-profile-info {
  display: flex;
  padding: 10px 20px;
  font-size: 14px;
  color: #666666;
  line-height: 28px;
}

.user-profile-info-title {
  width: 70px;
}

.menu-box {
  padding: 40px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.menu-list {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.menu-item {
  color: #303133;
  cursor: pointer;
  height: 56px;
  position: relative;
}

.menu-unread {
  position: absolute;
  top: -5px;
  right: 5px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  border-radius: 50%;
  background-color: #d02129;
  color: #ffffff;
}

.router-link-active i {
  color: #d02129 !important;
}

.iconfont {
  padding: 15px;
  font-size: 28px;
  color: #606266;
  cursor: pointer;
}

.iconfont:active {
  color: #d02129;
}

.home-main {
  padding: 0;
  flex: 1;
}

</style>
